package com.sky.controller.user;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.sky.result.Result;
import com.sky.service.user.UserOrderService;
import com.wechat.pay.java.core.Config;


import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
@Slf4j
public class WxPayController {
    @Autowired
    private Config config;
    @Autowired
    private NotificationConfig notificationConfig;
    @Autowired
    private UserOrderService userOrderService;

    /**
     * 测试支付成功语音通知
     */
    @GetMapping("/paySuc")
    public String mockPaySuccess(String mun){
        log.info("模拟用户支付成功");
        userOrderService.paySuccess(mun);
        return "OK";
    }
    /**
     * 测试催单语音通知
     */
    @GetMapping("/reminder/{orderId}")
    public Result<String> reminder(@PathVariable Long orderId){
        log.info("开始催单");
        String message=userOrderService.reminder(orderId);
        return Result.success(message);
    }

    /**
     * 订单支付
     */
    @GetMapping("/wxpay")
    public Result wxPay(){
        log.info("开始支付");
        NativePayService payService = new NativePayService.Builder().config(config).build();
        //构造参数
        PrepayRequest request = new PrepayRequest();
        request.setOutTradeNo("999999999999999999999");
        request.setDescription("测试支付");
        request.setNotifyUrl("http://localhost:8080/notify");
        request.setAppid("wx0ca99a203b1e9943");
        request.setMchid("1561414331");
        Amount amount = new Amount();
        amount.setTotal(1);
        amount.setCurrency("CNY");
        request.setAmount(amount);

        PrepayResponse response = payService.prepay(request);
        String codeUrl = response.getCodeUrl();
        QrCodeUtil.generate(codeUrl, 800, 800, new File("D:\\pay.jpg"));
        return Result.success();
    }
    /**
     * 订单查询
     */
    //当订单支付后，微信会通过回调地址发送通知，通知中包含订单号，通过订单号查询订单状态（也适用于没有收到通知，手动查询订单）
    @GetMapping("/query")
    public Result query(String num){
        log.info("开始查询");
        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
        request.setMchid("1561414331");
        request.setOutTradeNo(num);
        NativePayService payService = new NativePayService.Builder().config(config).build();
        Transaction transaction = payService.queryOrderByOutTradeNo(request);
        return Result.success(transaction);
    }
    //http://localhost:8080/wx/notify
    /**
     * 订单支付信息回调通知
     */
    @PostMapping("/wx/notify")
    public String wxNotify(@RequestBody JSONObject body, HttpServletRequest request){
        log.info("支付回调通知：{}",body);
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatPayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(wechatPayNonce)
                .signature(wechatSignature)
                .timestamp(wechatTimestamp)
                .body(body.toString())
                .build();
        NotificationParser notificationParser = new NotificationParser(notificationConfig);
        Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
        String outTradeNo = transaction.getOutTradeNo();
        log.info("支付成功，订单号：{}",outTradeNo);
        //todo 后续订单相关操作，改支付状态，发货，根据业务处理
        //处理成功，返回200 OK 状态码
        return ResponseEntity.status(HttpStatus.OK).toString();
    }
    /**
     * 退款订单
     */
    @GetMapping("/refund")
    public Result refund(){
        log.info("开始退款");
        RefundService refundService = new RefundService.Builder().config(config).build();
        CreateRequest createRequest = new CreateRequest();
        //构造退款参数
        createRequest.setNotifyUrl("http://localhost:8080/notify");
        createRequest.setOutTradeNo("999999999999999999999");
        createRequest.setOutRefundNo("888888888888888888888");
        createRequest.setReason("测试退款");
        AmountReq amountReq = new AmountReq();
        amountReq.setRefund(1L);
        amountReq.setCurrency("CNY");
        createRequest.setAmount(amountReq);
        Refund refund = refundService.create(createRequest);
        return Result.success(refund);
    }
}
